/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.serializer;

import java.util.Iterator;
import java.util.List;

import org.dailydev.wave.robot.IRobot;
import org.dailydev.wave.robot.RobotException;

import com.google.wave.api.Capability;
import com.google.wave.api.Context;

/**
 * Serializes {@link IRobot} in form of it's capabilities document.
 * 
 * @author Roman Bosak, DailyDev.org
 */
public class CapabilitiesSerializer implements ISerializer<IRobot> {

    /** {@inheritDoc} */
    @Override
    public IRobot deserialize(String json) throws RobotException {
        throw new UnsupportedOperationException("Capabilities document deserialization is not supported.");
    }

    /**
     * Generates capabilities.xml document based on configured handlers.
     */
    @Override
    public String serialize(IRobot robot) throws RobotException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        buffer.append("<w:robot xmlns:w=\"http://wave.google.com/extensions/robots/1.0\">\n");
        buffer.append("\t<w:version>").append(robot.getRobotVersion()).append("</w:version>\n");
        buffer.append("\t<w:capabilities>\n");

        for (Capability capability : robot.getCapabilities()) {
            buffer.append("\t\t<w:capability name=\"").append(capability.getEventType().toString()).append("\"");

            List<Context> contexts = capability.getContexts();
            if (contexts != null && !contexts.isEmpty()) {
                buffer.append(" context=\"");
                for (Iterator<Context> it = contexts.iterator(); it.hasNext();) {
                    Context context = it.next();
                    buffer.append(context.name());
                    if (it.hasNext()) {
                        buffer.append(',');
                    }
                }
                buffer.append("\"");
            }

            buffer.append(" />\n");
        }

        buffer.append("\t</w:capabilities>\n");
        buffer.append("</w:robot>\n");

        return buffer.toString();
    }
}
